
//
//  ViewController.m
//  Clock
//
//  Created by zc on 15/8/22.
//  Copyright (c) 2015年 zc. All rights reserved.
//

#import "ViewController.h"
#import "SetTimeViewController.h"
#import "CalendarHomeViewController.h"
#import "XXXRoundMenuButton.h"
#import "MapViewController.h"
#import "PhotoViewController.h"
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define TAG 777

@interface ViewController ()
{
    int _h,_m,_s,_interval;
    NSArray * title;
}
@property(nonatomic,retain)NSTimer * timer;
@property(nonatomic,retain)UILabel * minLabel;
@property(nonatomic,retain)UILabel * hourLabel;
@property(nonatomic,retain)UILabel * secondLabel;
@property(nonatomic,retain)UIView * min;
@property(nonatomic,retain)UIView * hour;
@property(nonatomic,retain)UIView * second;
@property (nonatomic, strong) CalendarHomeViewController * chvc;
@property (nonatomic, strong) XXXRoundMenuButton * menuBtn;
@property (nonatomic, strong) UIImageView * rebackImageView;
@end

@implementation ViewController

static int cnt;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _interval = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    [self createClock];
    [self addButton];
    [self createNumClock];
    [self createControlButton];
    [self createTimer];
    [self noti];
    [self compliet];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setUpNavi];
}

- (void)setUpNavi{
    self.navigationController.navigationBarHidden = YES;
}

- (void)noti
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTime:) name:@"clock" object:nil];
}

- (void)setTime:(NSNotification *)info_x
{
    NSArray * timeArrays = [info_x.userInfo allValues];
    NSArray * timeArray = timeArrays[0];
    _h = [timeArray[0] intValue];
    _m = [timeArray[1] intValue];
    _s = [timeArray[2] intValue];
    
    [self time];
}

#pragma mark - 设置按钮
- (void)addButton{
    
    self.menuBtn = [[XXXRoundMenuButton alloc] init];
    
    __weak typeof(self) weakSelf = self;
    
    [self.menuBtn loadButtonWithIcons:@[
                                           [UIImage imageNamed:@"icon_can"],
                                           [UIImage imageNamed:@"icon_pos"],
                                           [UIImage imageNamed:@"icon_img"]
                                           
                                           ] startDegree:-M_PI layoutDegree:M_PI/2];
    [self.menuBtn setButtonClickBlock:^(NSInteger idx) {
        
        NSLog(@"button %@ clicked !",@(idx));
        
        if (idx == 0) {
            [weakSelf jmpCalendar];
        }
        if (idx == 1) {
            [weakSelf jmpMap];
        }
        if (idx == 2) {
            [weakSelf jmpPhoto];
        }
        
    }];
    
    self.menuBtn.frame = CGRectMakeEx(0, 0, 200, 200);
    
    self.menuBtn.backgroundColor = [UIColor clearColor];
    
    self.menuBtn.centerButtonSize = CGSizeMake(44, 44);
    
    self.menuBtn.center = CGPointMake(SCREEN_WIDTH - 30, SCREEN_HEIGHT - 30);
    
    self.menuBtn.tintColor = [UIColor whiteColor];
    
    self.menuBtn.mainColor = [UIColor blackColor];
    
    [self.view addSubview:self.menuBtn];
}

#pragma mark   ########  转盘调时(分钟)
- (void)minRotation:(UIRotationGestureRecognizer *)minR
{
    CGFloat deg = [self radian:minR.rotation];
    minR.view.transform = CGAffineTransformMakeRotation(minR.rotation);
    int s = deg/0.1;
    int xs = s%60;
    int xm = ((s - xs)/60)%60;
    int xh = (s - (xm*60) - xs)/3600;
    
    _second.transform = CGAffineTransformMakeRotation([self degress:s*6]);
    _min.transform = CGAffineTransformMakeRotation([self degress:s*0.1]);
    _hour.transform = CGAffineTransformMakeRotation([self degress:s*(0.5/60)]);
    
    _h = xh;
    _m = xm;
    _s = xs;
    
    _hourLabel.text = [NSString stringWithFormat:@"%02d",_h];
    _minLabel.text = [NSString stringWithFormat:@":%02d",_m];
    _secondLabel.text = [NSString stringWithFormat:@":%02d",_s];
}
#pragma mark  ######   转盘调时（时针）
- (void)hourRotation:(UIRotationGestureRecognizer *)hourR
{
    CGFloat deg = [self radian:hourR.rotation];
    hourR.view.transform = CGAffineTransformMakeRotation(hourR.rotation);
    int s = deg/(0.5/60);
    int xs = s%60;
    int xm = ((s - xs)/60)%60;
    int xh = (s - (xm*60) - xs)/3600;
    
    _second.transform = CGAffineTransformMakeRotation([self degress:s*6]);
    _min.transform = CGAffineTransformMakeRotation([self degress:s*0.1]);
    _hour.transform = CGAffineTransformMakeRotation([self degress:s*(0.5/60)]);
    
    _h = xh;
    _m = xm;
    _s = xs;
    
    _hourLabel.text = [NSString stringWithFormat:@"%02d",_h];
    _minLabel.text = [NSString stringWithFormat:@":%02d",_m];
    _secondLabel.text = [NSString stringWithFormat:@":%02d",_s];
}

- (void)createClock
{
#pragma mark ########### 表盘
    _second = [[UIView alloc]initWithFrame:CGRectMake(widthEx(40), heightEx(40), widthEx(295), widthEx(295))];
    _second.backgroundColor = [UIColor whiteColor];
    _second.layer.cornerRadius = widthEx(295)/2;
    _second.layer.borderColor = [UIColor blackColor].CGColor;
    _second.layer.borderWidth = 5;
    [self.view addSubview:_second];
    
    
    _min = [[UIView alloc]initWithFrame:CGRectMake(widthEx(50), heightEx(50), widthEx(275), widthEx(275))];
    _min.backgroundColor = [UIColor blackColor];
    _min.layer.cornerRadius = widthEx(275)/2;
    _min.tag = 23;
    [_min addGestureRecognizer:[[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(minRotation:)]];
    [self.view addSubview:_min];
    
    _hour = [[UIView alloc]initWithFrame:CGRectMake(widthEx(100), heightEx(100), widthEx(175), widthEx(175))];
    _hour.backgroundColor = [UIColor whiteColor];
    _hour.layer.cornerRadius = widthEx(175)/2;
    _hour.tag = 24;
    [_hour addGestureRecognizer:[[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(hourRotation:)]];
    [self.view addSubview:_hour];
    
#pragma mark   ####### 时分秒针
    UILabel * secondPoint = [[UILabel alloc]initWithFrame:CGRectMakeEx(144, 5, 7, 10)];
    secondPoint.backgroundColor = [UIColor redColor];
    [_second addSubview:secondPoint];
    
    UILabel * minPoint = [[UILabel alloc]initWithFrame:CGRectMakeEx(134, 5, 7, 40)];
    minPoint.backgroundColor = [UIColor whiteColor];
    [_min addSubview:minPoint];
    
    UILabel * hourPoint = [[UILabel alloc]initWithFrame:CGRectMakeEx(84, 5, 7, 50)];
    hourPoint.backgroundColor = [UIColor blackColor];
    [_hour addSubview:hourPoint];
    
    
    UIButton * centerPoint = [UIButton buttonWithType:UIButtonTypeCustom];
    centerPoint.frame = CGRectMakeEx(84, 84, 7, 7);
    centerPoint.backgroundColor = [UIColor blackColor];
    centerPoint.layer.cornerRadius = 3.5;
    [_hour addSubview:centerPoint];
}

- (void)jmpPhoto{
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = @"cube";
    transition.subtype = kCATransitionFromRight;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    PhotoViewController * photo = [[PhotoViewController alloc] init];
    [self.navigationController pushViewController:photo animated:YES];
}

- (void)jmpMap{
    
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = @"rippleEffect";
    transition.subtype = kCATransitionFromRight;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    MapViewController * map = [[MapViewController alloc] init];

    [self.navigationController pushViewController:map animated:YES];
}

- (void)jmpCalendar{
    if (!_chvc) {
        
        _chvc = [[CalendarHomeViewController alloc]init];
        _chvc.calendartitle = @"Time goes by";
        [_chvc setAirPlaneToDay:365 ToDateforString:nil];
        
        
        
    }
//    __weak typeof(self) weakSelf = self;
//    _chvc.calendarblock = ^(CalendarDayModel *model){
//        
//        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//
//        if(sender.view.tag==101)//开始时间
//        {
//            if(![weakSelf.checkdateView.labdateend.text isEqualToString:@"请选择时间"])
//            {
//                NSString *statrDate=[model toString];
//                NSString *endDate=weakSelf.checkdateView.labdateend.text;
//                
//                NSDate *date1=[dateFormatter dateFromString:statrDate];
//                NSDate *date2=[dateFormatter dateFromString:endDate];
//                
//                NSTimeInterval time=[date2 timeIntervalSinceDate:date1];
//                
//                if(time<=0)
//                {
//                    [MBProgressHUD showError:@"开始时间必须早于结束时间"];
//                }
//                else
//                {
//                    weakSelf.checkdateView.labdatestart.text=[model toString];
//                    [weakSelf getinfobylog:weakSelf.typeidArray[weakSelf.thispage] gr_id:[LXAccountTool account].morenlaorenID];
//                }
//            }
//            else
//            {
//                weakSelf.checkdateView.labdatestart.text=[model toString];
//                
//            }
//        }
//        else
//        {
//            if(![weakSelf.checkdateView.labdatestart.text isEqualToString:@"请选择时间"])
//            {
//                NSString *statrDate=weakSelf.checkdateView.labdatestart.text;
//                NSString *endDate=[model toString];
//                
//                NSDate *date1=[dateFormatter dateFromString:statrDate];
//                NSDate *date2=[dateFormatter dateFromString:endDate];
//                
//                NSTimeInterval time=[date2 timeIntervalSinceDate:date1];
//                
//                if(time<=0)
//                {
//                    [MBProgressHUD showError:@"结束时间必须晚于开始时间"];
//                }
//                else
//                {
//                    weakSelf.checkdateView.labdateend.text=[model toString];
//                    [weakSelf getinfobylog:weakSelf.typeidArray[weakSelf.thispage] gr_id:[LXAccountTool account].morenlaorenID];
//                }
//            }
//            else
//            {
//                weakSelf.checkdateView.labdateend.text=[model toString];
//            }
//        }
//    };

    
    _chvc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:_chvc];
    
    [self.navigationController presentViewController:navi animated:YES completion:nil];
}

- (void)createNumClock
{
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMakeEx(40, 345, 295, 20)];
    label.text = @"Zchen Time 〇";
    label.tag = 99;
    label.textColor = [UIColor blackColor];
    [self.view addSubview:label];
    label.textAlignment = NSTextAlignmentCenter;
//    label.userInteractionEnabled = YES;
//    [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jmpCalendar:)]];
    

#pragma mark   ####### 数字时钟
    _hourLabel = [[UILabel alloc]initWithFrame:CGRectMakeEx(96, 365, 61, 40)];
    _hourLabel.text = @"00"; _hourLabel.tag = TAG + 12;
    _hourLabel.textAlignment = NSTextAlignmentRight;
    _hourLabel.font = [UIFont fontWithName:@"Chalkduster" size:24];
    _hourLabel.textColor = [UIColor blackColor];
    [self.view addSubview:_hourLabel];
    _minLabel = [[UILabel alloc]initWithFrame:CGRectMakeEx(157, 365, 61, 40)];
    _minLabel.text = @":00"; _minLabel.tag = TAG + 13;
    _minLabel.textAlignment = NSTextAlignmentCenter;
    _minLabel.font = [UIFont fontWithName:@"Chalkduster" size:24];
    _minLabel.textColor = [UIColor blackColor];
    [self.view addSubview:_minLabel];
    _secondLabel = [[UILabel alloc]initWithFrame:CGRectMakeEx(218, 365, 61, 40)];
    _secondLabel.text = @":00"; _secondLabel.tag = TAG + 14;
    _secondLabel.textAlignment = NSTextAlignmentLeft;
    _secondLabel.font = [UIFont fontWithName:@"Chalkduster" size:24];
    _secondLabel.textColor = [UIColor blackColor];
    [self.view addSubview:_secondLabel];
}

- (void)createControlButton
{
    title = @[@"系统时间",@"设置"];
    for (int i = 0; i < 2; i++)
    {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMakeEx(110, 415 + i*40, 155, 30);
        button.backgroundColor = [UIColor blackColor];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:17];
        button.layer.cornerRadius = 5;   button.tag = TAG+i;
        [button setTitle:title[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
}

- (void)cleanZero{
    _h = 0;
    _m = 0;
    _s = 0;
    [self time];
    [_timer setFireDate:[NSDate distantFuture]];
}

- (void)createTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:_interval target:self selector:@selector(run) userInfo:nil repeats:YES];
}

- (void)reback{
    
}

- (void)buttonAction:(UIButton *)button
{
    if ([button.titleLabel.text isEqualToString:@"开始/暂停"]) {
        cnt++;
        if (cnt % 2) {
            [_timer setFireDate:[NSDate distantPast]];
        }else
        {
            [_timer setFireDate:[NSDate distantFuture]];
        }
    }
    
    if ([button.titleLabel.text isEqualToString:@"系统时间"])
    {
        [self systemTime];
        [self.timer setFireDate:[NSDate distantPast]];
    }
    
    if ([button.titleLabel.text isEqualToString:@"设置"])
    {
        SetTimeViewController * a = [[SetTimeViewController alloc]init];
        a.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentViewController:a animated:YES completion:nil];
    }
}


#pragma mark   ######弧度。角度相互转化
- (CGFloat)degress:(CGFloat)deg
{
    return deg * M_PI/180;
}

- (CGFloat)radian:(CGFloat)rad
{
    return rad/(M_PI/180);
}

- (void)compliet
{
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMakeEx(40, 495, 295, 30)];
    label.text = @"时间，不在于你拥有多少，而在于你怎样使用";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:12];
    label.numberOfLines = 0;
    
    UILabel * label1 = [[UILabel alloc]initWithFrame:CGRectMakeEx(40, 525, 295, 30)];  
    label1.textColor = [UIColor blackColor];
    label1.font = [UIFont systemFontOfSize:12];
    label1.numberOfLines = 0;
    label1.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:label];
    [self.view addSubview:label1];
    
    UILabel * label2 = [[UILabel alloc]initWithFrame:CGRectMakeEx(40, 555, 295, 30)];
    label2.text = @"2015.8.22 张晨 客居京华";
    label2.font = [UIFont systemFontOfSize:10];
    label2.textAlignment = NSTextAlignmentCenter;
    label2.textColor = [UIColor blackColor];
    [self.view addSubview:label2];
    
    UILabel * label3 = [[UILabel alloc]initWithFrame:CGRectMakeEx(40, 585, 295, 30)];
    label3.text = @"执笔流年，浮生若梦";
    label3.font = [UIFont systemFontOfSize:9];
    label3.textAlignment = NSTextAlignmentCenter;
    label3.textColor = [UIColor blackColor];
    [self.view addSubview:label3];
}

- (void)run
{
    _s++;
    if (_s >= 60)
    {
        _m++;
        _s = 0;
    }
    if (_m >= 60)
    {
        _h++;
        _m = 0;
    }
    if (_h >= 24)
    {
        _s = 0;
        _m = 0;
        _h = 0;
    }
    
    [self time];
}

- (void)time
{
    _hourLabel.text = [NSString stringWithFormat:@"%02d",_h];
    _minLabel.text = [NSString stringWithFormat:@":%02d",_m];
    _secondLabel.text = [NSString stringWithFormat:@":%02d",_s];
    
    _second.transform = CGAffineTransformMakeRotation([self degress:_s*6]);
    _min.transform = CGAffineTransformMakeRotation([self degress:(_m*60+_s)*0.1]);
    _hour.transform = CGAffineTransformMakeRotation([self degress:(_h*3600+_m*60+_s)*(0.5/60)]);
}

#pragma mark   ######  获取系统时间
- (void)systemTime
{
    UILabel * label = (UILabel *)[self.view viewWithTag:99];
    NSArray * time_all = [[self getSystemTime] componentsSeparatedByString:@" "];
    NSArray * time_hms = [time_all[1] componentsSeparatedByString:@":"];
    label.text = time_all[0];
    _h = [time_hms[0] intValue];
    _m = [time_hms[1] intValue];
    _s = [time_hms[2] intValue];
    
    _hourLabel.text = [NSString stringWithFormat:@"%02d",_h];
    _minLabel.text = [NSString stringWithFormat:@":%02d",_m];
    _secondLabel.text = [NSString stringWithFormat:@":%02d",_s];
    
    [self time];
}

- (NSString *)getSystemTime
{
    NSDate * time = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
    NSString * day = [dateFormatter stringFromDate:time];
    return day;
}

@end
